<template>
  <div class="mpd-side-panel-key-value-manage">
    <h4 class="margin-xs">
      <slot name="title">{{ title }}</slot>
    </h4>
    <a-input-group v-for="(item, index) in value" :key="index" compact>
      <mpd-tooltip
        :visible="!!item.key && !isCssVariableName(item.key)"
        placement="topLeft"
        title="只能是字母、数字、下划线、减号组成，不能以数字开头"
      >
        <a-input v-if="!keyEnum || keyEnum.length === 0" style="width: 40%" v-model="item.key" allowClear />
        <a-auto-complete
          v-else
          v-model="item.key"
          :data-source="keyDataSource"
          allowClear
          style="width: 40%"
          @search="onKeySearch"
        />
      </mpd-tooltip>
      <a-input style="width: 50%" v-model="item.value" allowClear />
      <a-button style="width: 10%" class="padding-no" @click="value.splice(index, 1)">
        <mpd-icon icon="mpd-icon-shanchu"></mpd-icon>
      </a-button>
    </a-input-group>
    <div class="padding-xs">
      <a-button type="dashed" block size="small" @click="addArrayItem(value)"> + </a-button>
    </div>
  </div>
</template>

<script>
import { isCssVariableName } from '@/util/regexUtil'

export default {
  props: {
    // 标题
    title: {
      type: String,
      default() {
        return ''
      }
    },
    // 处理的值
    value: {
      type: Array,
      required: true
    },
    // key枚举
    keyEnum: {
      type: Array
    }
  },
  data() {
    return {
      keyDataSource: []
    }
  },
  methods: {
    isCssVariableName,
    // 添加数组元素
    addArrayItem(array) {
      array.push({
        key: '',
        value: ''
      })
    },
    // key自动完成过滤值
    onKeySearch(searchText) {
      this.keyDataSource = this.keyEnum.filter(val => val.indexOf(searchText) > -1)
    }
  }
}
</script>
